/*
 * @Author: Suo-Yuheng syh15399227325@163.com
 * @Date: 2025-09-09 19:32:58
 * @LastEditors: Suo-Yuheng syh15399227325@163.com
 * @LastEditTime: 2025-09-09 22:00:01
 * @FilePath: /0909/ServerCal.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

// 利用 提供网络通信服务的 服务器，把 网络计算器的 请求 和 响应 结合

#pragma once

#include <iostream>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper,
};

class Calculator
{
public:
    Calculator()
    {
    }

    Response CalculatorHelper(const Request &req)
    {
        Response temp;
        switch (req.op)
        {
            case '+':
                temp.result = req.x + req.y;
                break;
            case '-':
                temp.result = req.x - req.y;
                break;
            case '*':
                temp.result = req.x * req.y;
                break;
            case '/':
                if (req.y == 0)
                {
                    temp.result = -1;
                    temp.code = Div_Zero;
                }
                else
                {
                    temp.result = req.x / req.y;
                }
                break;
            case '%':
                if (req.y == 0)
                {
                    temp.result = -1;
                    temp.code = Mod_Zero;
                }
                else
                {
                    temp.result = req.x % req.y;
                }
                break;
            default:
                temp.code = Other_Oper;
                break;
        }
        return temp;
    }

    std::string Handler(std::string &package) // 收到 报文，对报文作处理
    {
        std::string content;
        bool r = Decode(package, &content);
        if (!r)
            return ""; // 报文不完整或者有问题

        Request req;
        r = req.Deserialize(content);
        if (!r)
            return ""; // 反序列化失败

        Response resp = CalculatorHelper(req); // 计算

        content = "";              // 清空
        resp.Serialize(&content);  // 序列化
        package = Encode(content); // 添加报头

        return package;
    }

    ~Calculator()
    {
    }
};
